package com.autumn.platform.web.resulthandler.wrapper.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Page;

import com.autumn.platform.web.annotation.JsonBody;

public class PageResultWrapper extends MapResultWrapper {

    private PageProperties pageProperties = new PageProperties();

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public boolean supports(Object result, MethodParameter resultType) {
        return Page.class.isAssignableFrom(resultType.getMethod().getReturnType());
    }

    @Override
    protected void doWrap(Map<String, Object> wrapper, Object result) {
        Map<String, Object> meta = new HashMap<String, Object>();
        PageProperties pageProperties = this.getPageProperties();
        wrapper.put(pageProperties.getMetaPropertyName(), meta);
        Page<?> page = (Page<?>) result;

        wrapper.put(pageProperties.getDataPropertyName(), ((Page<?>) result).getContent());
        meta.put(pageProperties.getSizePropertyName(), page.getSize());
        meta.put(pageProperties.getPagePropertyName(), page.getNumber());
        meta.put(pageProperties.getTotalPropertyName(), page.getTotalElements());
    }

    @Override
    protected void doWrapValue(Map<String, Object> wrap, Object result, MethodParameter resultType, JsonBody jsonBody) {
        // empty
    }

    public PageProperties getPageProperties() {
        return pageProperties;
    }

    public void setPageProperties(PageProperties pageProperties) {
        this.pageProperties = pageProperties;
    }
}
